package ua.com.stormlabs.tiny.licenseserver.storage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * @author Denis Bondarenko
 * @version 1.0 3/31/11
 */
@Component
public class StorageTestHelperImpl implements StorageTestHelper {

    private static final Logger log = LoggerFactory.getLogger(StorageTestHelperImpl.class);

    @PersistenceContext
    private EntityManager entityManager;


    @Override
    public void clearTables(Class... entityClasses) {
        for (Class entityClass : entityClasses) {
            String entityName = entityManager.getEntityManagerFactory().getMetamodel().entity(entityClass).getName();
            log.info("Deleting entity '" + entityName + "' items");
            String hql = "from " + entityName;
            List result = entityManager.createQuery(hql).getResultList();
            for (Object entity : result) {
                entityManager.remove(entity);
            }
            entityManager.flush();
        }
    }
}
